package com.ruoyi.training.service.impl;

import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.training.domain.ClassCheckin;
import com.ruoyi.training.domain.TrainingClass;
import com.ruoyi.training.dto.TrainingClassBatchDTO;
import com.ruoyi.training.mapper.ClassCheckinMapper;
import com.ruoyi.training.mapper.TrainingClassMapper;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.mapper.TrainingScheduleMapper;
import com.ruoyi.training.domain.TrainingSchedule;
import com.ruoyi.training.service.ITrainingScheduleService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 培训计划明细（单节课程/活动）Service业务层处理
 *
 * @author WorrilessGo
 * @date 2025-09-24
 */
@Service
public class TrainingScheduleServiceImpl implements ITrainingScheduleService {
    private static final SnowflakeIdUtils snowflake = new SnowflakeIdUtils(5, 8);

    @Autowired
    private TrainingScheduleMapper trainingScheduleMapper;

    @Autowired
    private ClassCheckinMapper classCheckinMapper;

    @Autowired
    private TrainingClassMapper trainingClassMapper;

    /**
     * 查询培训计划明细（单节课程/活动）
     *
     * @param trainingScheduleId 培训计划明细（单节课程/活动）主键
     * @return 培训计划明细（单节课程/活动）
     */
    @Override
    public TrainingSchedule selectTrainingScheduleByTrainingScheduleId(String trainingScheduleId) {
        return trainingScheduleMapper.selectTrainingScheduleByTrainingScheduleId(trainingScheduleId);
    }

    /**
     * 查询培训计划明细（单节课程/活动）列表
     *
     * @param trainingSchedule 培训计划明细（单节课程/活动）
     * @return 培训计划明细（单节课程/活动）
     */
    @Override
    public List<TrainingSchedule> selectTrainingScheduleList(TrainingSchedule trainingSchedule) {
        return trainingScheduleMapper.selectTrainingScheduleList(trainingSchedule);
    }

    /**
     * 新增培训计划明细（单节课程/活动）
     *
     * @param trainingSchedule 培训计划明细（单节课程/活动）
     * @return 结果
     */
    @Override
    public int insertTrainingSchedule(TrainingSchedule trainingSchedule) {
        trainingSchedule.setTrainingScheduleId(String.valueOf(snowflake.nextId()));
        trainingSchedule.setCreateTime(DateUtils.getNowDate());
        trainingSchedule.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        int result = trainingScheduleMapper.insertTrainingSchedule(trainingSchedule);
        //修改班级表中培训计划设置状态
        TrainingClass trainingClass = new TrainingClass();
        if (trainingSchedule.getTrainingClassId() != null && !"".equals(trainingSchedule.getTrainingClassId()))
        trainingClass.setTrainingClassId(trainingSchedule.getTrainingClassId());
        trainingClass.setTrainingPlanDesc("已设置");
        trainingClassMapper.updateTrainingClass(trainingClass);
        return result;
    }

    /**
     * 修改培训计划明细（单节课程/活动）
     *
     * @param trainingSchedule 培训计划明细（单节课程/活动）
     * @return 结果
     */
    @Override
    public int updateTrainingSchedule(TrainingSchedule trainingSchedule) {
        trainingSchedule.setUpdateTime(DateUtils.getNowDate());
//        trainingSchedule.setUpdateBy("张三");
        trainingSchedule.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        return trainingScheduleMapper.updateTrainingSchedule(trainingSchedule);
    }

    /**
     * 批量删除培训计划明细（单节课程/活动）
     *
     * @param trainingScheduleIds 需要删除的培训计划明细（单节课程/活动）主键
     * @return 结果
     */
    @Override
    public int deleteTrainingScheduleByTrainingScheduleIds(String[] trainingScheduleIds) {
        return trainingScheduleMapper.deleteTrainingScheduleByTrainingScheduleIds(trainingScheduleIds);
    }

    /**
     * 删除培训计划明细（单节课程/活动）信息
     *
     * @param trainingScheduleId 培训计划明细（单节课程/活动）主键
     * @return 结果
     */
    @Override
    public int deleteTrainingScheduleByTrainingScheduleId(String trainingScheduleId) {
        //判断该培训计划是否已经关联签到
        ClassCheckin classCheckin =  classCheckinMapper.selectClassCheckinByTrainingScheduleId(trainingScheduleId);
        if (classCheckin != null){
            return 100;
        }

        TrainingSchedule trainingSchedule = trainingScheduleMapper.selectTrainingScheduleByTrainingScheduleId(trainingScheduleId);
        int result = trainingScheduleMapper.deleteTrainingScheduleByTrainingScheduleId(trainingScheduleId);
        //判断班级中是否还有培训计划
        String trainingClassId = trainingSchedule.getTrainingClassId();
        List<TrainingSchedule> trainingSchedules = trainingScheduleMapper.selectByClassId(trainingClassId);
        if (trainingSchedules == null || trainingSchedules.isEmpty()) {
            //若没有培训计划，修改班级表中培训计划设置状态
            TrainingClass trainingClass = new TrainingClass();
            trainingClass.setTrainingClassId(trainingClassId);
            trainingClass.setTrainingPlanDesc("");
            trainingClassMapper.updateTrainingClass(trainingClass);
        }
        return result;
    }

    /**
     * 批量新增培训计划明细（单节课程/活动）
     * lqx
     *
     * @param trainingSchedules 培训计划明细（单节课程/活动）列表
     * @return 结果
     */
    @Override
    @Transactional
    public int batchInsertTrainingSchedule(List<TrainingSchedule> trainingSchedules) {
        if (trainingSchedules == null || trainingSchedules.isEmpty()) {
            return 0;
        }
        // 可以在这里添加统一的创建时间、创建人等公共字段设置
        for (TrainingSchedule schedule : trainingSchedules) {
            schedule.setTrainingScheduleId(String.valueOf(snowflake.nextId()));
            // 如果需要统一设置创建信息，可以在这里处理
            schedule.setCreateBy(SecurityUtils.getUsername());
            schedule.setCreateTime(new Date());
        }
        return trainingScheduleMapper.batchInsertTrainingSchedule(trainingSchedules);
    }

    /**
     * 批量更新班级的培训计划（先删除该班级所有计划，再新增传递的列表）
     * lqx
     */
    @Override
    @Transactional // 确保删除和新增在同一事务中
    public int batchUpdateByClass(TrainingClassBatchDTO batchDTO) {
        String classId = batchDTO.getTrainingClassId();
        List<TrainingSchedule> schedules = batchDTO.getTrainingSchedules();

        // 1. 删除该班级下所有已有记录
        int deleteCount = trainingScheduleMapper.deleteByClassId(classId);

        // 2. 处理新增列表（若列表为空，则只执行删除）
        int insertCount = 0;
        if (schedules != null && !schedules.isEmpty()) {
            // 强制统一所有计划的班级ID为DTO中的班级ID
            String username = SecurityUtils.getUsername();
            Date now = new Date();
            for (TrainingSchedule schedule : schedules) {
                // 强制覆盖班级ID
                schedule.setTrainingClassId(classId);
                // 生成主键
                schedule.setTrainingScheduleId(String.valueOf(snowflake.nextId()));
                // 设置公共字段
                schedule.setCreateBy(username);
                schedule.setCreateTime(now);
                schedule.setUpdateBy(username);
                schedule.setUpdateTime(now);
            }
            // 批量新增
            insertCount = trainingScheduleMapper.batchInsertTrainingSchedule(schedules);
        }

        // 返回总操作数（删除数+新增数）
        return deleteCount + insertCount;
    }

    /**
     * 通过班级ID查询培训计划列表
     * lqx
     * @param trainingClassId 班级ID
     * @return 培训计划列表
     */
    @Override
    public List<TrainingSchedule> selectByClassId(String trainingClassId) {
        // 调用Mapper层查询
        return trainingScheduleMapper.selectByClassId(trainingClassId);
    }

}
